<template>
	<view class="container">
		<view class="example">
			<uni-section title="个人信息" type="line" padding>
				<!-- 表单展示 -->
				<uni-forms class="form-row" ref="baseForm" :model="baseFormData" v-if="baseFormData" labelWidth="90px">
					<uni-forms-item class="label" label="报警器类型">
						<uni-data-checkbox v-model="baseFormData.type" :localdata="types" mode="list">
							{{ baseFormData.type === 0 ? '看护报警器' : '氧舱报警器' }}
						</uni-data-checkbox>
					</uni-forms-item>
					<uni-forms-item class="label" label="名称">
						<uni-easyinput v-model="baseFormData.name">{{ baseFormData.name }}</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item class="label" label="年龄">
						<uni-easyinput v-model="baseFormData.age">{{ baseFormData.age }}</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item class="label" label="性别">
						<uni-data-checkbox v-model="baseFormData.sex":localdata="sexs">
							{{ baseFormData.sex === '男' ? '男' : '女'}}
						</uni-data-checkbox>
					</uni-forms-item>
					<uni-forms-item class="label" label="地址">
						<uni-easyinput v-model="baseFormData.address">{{ baseFormData.address}}</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item class="label" label="自定义信息">
						<uni-easyinput v-model="baseFormData.bed">{{ baseFormData.bed}}</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item class="label" label="其他备注">
						<uni-easyinput type="textarea"
							v-model="baseFormData.introduction">{{ baseFormData.introduction }}</uni-easyinput>
					</uni-forms-item>
				</uni-forms>
			</uni-section>

			<uni-section title="播报记录" type="line" padding>
				<scroll-view scroll-y class="tips-panel">
					<view class="panel-list" v-for="(item, index) in formattedLogs" :key="index">
						{{ item }}
					</view>
				</scroll-view>
			</uni-section>

			<uni-section title="其他功能" type="line" padding>
				<button style="margin-top: 15rpx;" @click="toggleAudioSource">
					{{ audioChoice[deviceUUID] === 'custom' ? '切换到普通话播报' : '切换到方言播报' }}
				</button>
				<button v-if="baseFormData.type === 1" type="default" plain="true" style="margin-top: 30rpx;"
					@click="callDevice">呼叫设备</button>
				<button type="default" plain="true" style="margin-top: 30rpx;" @click="addVoice">设置方言播报录音</button>
				<button type="default" plain="true" style="margin-top: 30rpx;" @click="setAlarm">设置闹钟提醒</button>
				<button type="default" plain="true" style="margin-top: 30rpx;" @click="setWifi">设备WiFi设置</button>
				<button type="primary" plain="true" style="margin-top: 30rpx;" @click="setResponseWord">设置收到提醒</button>
				<button type="primary" style="margin-top: 30rpx;" @click="saveChanges">保存更改</button>
				<button type="primary" style="margin-top: 15rpx;" @click="del">删除设备</button>
			</uni-section>
		</view>
		<view>
			<uni-popup ref="responseDialog" type="dialog">
				<uni-popup-dialog ref="responseClose"  mode="base" title="选择播放音频" @confirm="responseDialogConfirm">
					<uni-forms-item label="播放音频">
						<uni-data-checkbox v-model="selectedResponseWord" :localdata="reponseWord" mode="list"/>
						 
					</uni-forms-item>
				</uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import {
		client
	} from '../../main.js';
	export default {
		data() {
			return {
				// 等待从后端加载真实数据
				baseFormData: {
					type: '',
					name: '',
					age: '',
					sex: '',
					address: '',
					bed: '',
					introduction: '',
					phone: uni.getStorageSync('userPhoneNumber'),
				},
				sexs: [
					{text: '男', value: '男'}, 
					{text: '女', value: '女'},
					],
				types: [
					{text: '看护报警器', value: 0., "disable":true}, 
					{text: '看护氧舱报警器', value: 1,"disable":true},
					],
				reponseWord: [
					{text: '马上到', value: 0}, 
					{text: '马上来', value: 1}, 
					{text: '好的,收到了', value: 2},
					],
				/* multiArray: [
					['-区', 'A区', 'B区', 'C区'],
					['-楼', '1楼', '2楼', '3楼', '4楼', '5楼', '6楼', '7楼'],
					['-房', '1房', '2房', '3房', '4房', '5房', '6房', '7房'],
					['-床', '1床', '2床', '3床', '4床']
				],
				bed: [0, 0, 0, 0], */
				//mqtt有关值初始化
				subscribeInfo: [],
				publishInfo: {topic: '', qos: 0, message: '{"msg":"isFirstBond"}'},
				deviceUUID: '',
				// isBuffer: false,
				logs: '',
				messageListenerSet: false, // 新增变量，确保监听器只设置一次
				audioChoice: {}, // 记录每个设备的音频选择
				selectedResponseWord: null,
			}
		},
		computed: {
			formattedLogs() {
				if (!this.logs) return [];
				return this.logs.split('%').map(item => item.trim()).filter(item => item).reverse();
			}
		},
		onLoad(options) {
			if (options.uuid) {
				this.deviceUUID = options.uuid;
				this.fetchFormData(this.deviceUUID); //根据deviceUUID从后端获取用户信息
				this.loadAudioChoice(this.deviceUUID); // 加载音频选择

			}
			//异步存储deviceUUID
			uni.setStorage({
				key: 'deviceUUID',
				data: this.deviceUUID,
				success: (res) => {console.log('deviceUUID保存成功', this.deviceUUID);},
				fail: (err) => {console.log('deviceUUID保存失败', err);}
			});
			//每秒从后端获取一次日志
			this.pollData();
		},

		methods: {
			loadAudioChoice(uuid) {
				const choice = uni.getStorageSync(`audioChoice_${uuid}`);
				this.audioChoice[uuid] = choice || 'default';
			},

			toggleAudioSource() {
				const currentChoice = this.audioChoice[this.deviceUUID];
				const newChoice = currentChoice === 'custom' ? 'default' : 'custom';
				this.audioChoice[this.deviceUUID] = newChoice;
				uni.setStorageSync(`audioChoice_${this.deviceUUID}`, newChoice); // 使用同步方法保存选择
				// 发送 MQTT 消息到 'LSY/app/' + this.deviceUUID
				console.log("choice", this.audioChoice)
				const topic = 'LSY/app/' + this.deviceUUID;
				const message = JSON.stringify({msg: "audio_config", data: {choice: newChoice}});

				client.publish(topic, message, {qos: 0}, (err) => {
					if (err) {
						console.error(`Failed to publish message to ${topic}:`, err);
					} else {
						console.log(`Published message to ${topic}:`, message);
					}
				});
				uni.showToast({icon: 'success', duration: 1000});
				// 使用setTimeout延迟navigateBack的调用
				setTimeout(() => {uni.navigateBack();}, 1000); // 延迟1秒后返回
			},

			pollData() {
				this.logFetchInterval = setInterval(() => {this.fetchLogs();}, 2000); // 每2秒获取一次
			},
			fetchFormData(uuid) {
				uni.request({
					url: this.$baseUrl + `/user/device/getbyuuid/${uuid}`, // 使用模板字符串
					header: {
						'content-type': 'application/x-www-form-urlencoded', // 设置请求头
						'token': uni.getStorageSync('token')
					},
					method: 'GET',
					success: (res) => {
						console.log('Response:', res); // 日志记录响应
						if (res.statusCode === 200 && res.data && res.data.data) {
							this.baseFormData = res.data.data;
						} else {
							uni.showToast({title: '加载失败: ' + res.data.message, icon: 'none'});
						}
					},
					fail: (error) => {
						console.log('Request Failed:', error); // 日志记录错误
						uni.showToast({title: '请求失败', icon: 'none'});
					}
				});
			},

			fetchLogs() {
				uni.request({
					url: this.$baseUrl + `/user/device/get/logs/${this.deviceUUID}`, // 后端获取日志的接口
					header: {
						'token': uni.getStorageSync('token')
					},
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.data) {
							this.logs = res.data.data.join('%');
						} else {
							// console.error('获取日志失败：', res);
						}
					},
					fail: (err) => {
						console.error('请求日志失败：', err);
					}
				});
			},

			addVoice() {
				const uuid = this.deviceUUID; // 获取deviceUUID
				uni.navigateTo({url: `/pages/voice/voice?uuid=${uuid}`})
			},

			del() {
				// 发起HTTP DELETE请求以删除设备
				uni.request({
					url: this.$baseUrl + `/user/device/deletebyphone/${this.deviceUUID}/phone/` + 
						uni.getStorageSync('userPhoneNumber'), // 修改为你的删除API的URL					
					header: {
						//'content-type': 'application/x-www-form-urlencoded',
						'token': uni.getStorageSync('token')
					},
					method: 'DELETE', 
					success: (res) => {
						console.log(res);
						if (res.statusCode === 200) {
							uni.showToast({title: '删除成功', icon: "success", duration: 2000});
							this.endSubscribe();
							clearInterval(this.logFetchInterval);
							uni.navigateBack({url: '/pages/index/index',});
						} else {
							uni.showToast({
								title: '删除失败: ',
								icon: "fail",
								duration: 2000
							});
						}
					},
					fail: (err) => {
						console.error('请求错误：', err);
						uni.showToast({
							title: '请求错误',
							icon: "fail",
							duration: 2000
						});
					}
				});
			},

			saveChanges() {
				//保存数据到后端
				this.baseFormData.deviceUUID = this.deviceUUID;
				this.baseFormData.responseWord = this.selectedResponseWord;
				// this.baseFormData.bed = this.bed;
				console.log(this.baseFormData);
				uni.request({
					url: this.$baseUrl + '/user/device/update/phone/' + uni.getStorageSync('userPhoneNumber') +
						'/device',
					method: 'POST',
					data: this.baseFormData,
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'token': uni.getStorageSync('token')
					},
					success: (res) => {
						if (res.data.code === 0) {
							console.log('修改成功', res);
							uni.showToast({title: '修改成功', duration: 2000});
						} else {
							console.error('修改失败：', res);
							uni.showToast({
								title: '修改失败:手机号无权限 ',
								icon: 'none',
								duration: 2000
							});
						}
					},
					fail: (err) => {
						console.error('请求错误：', err);
						uni.showToast({
							title: '请求错误',
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
			/* 取消订阅*/
			endSubscribe() {
				let opts = {topic: 'LSY/device/' + this.deviceUUID}
				this.$mqttTool.unsubscribe(opts).then(res => {
					console.log('取消订阅成功', res);
				})
			},
			setAlarm() {
				const uuid = this.deviceUUID;
				uni.navigateTo({url: `/pages/alarm/alarm?uuid=${uuid}`})
			},
			setWifi() {
				const uuid = this.deviceUUID;
				uni.navigateTo({url: `/pages/wifi/wifi?uuid=${uuid}`})
			},
			setResponseWord() {
				uni.request({
					url: this.$baseUrl + `/user/device/getdeviceresponseword/${this.deviceUUID}`, // 后端获取响应音频类型
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'token': uni.getStorageSync('token')
					},
					method: 'GET',
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.data) {
							this.responseWord = res.data.data;
						} else {
							// console.error('获取响应音频类型失败：', res);
						}
					},
					fail: (err) => {console.error('请求响应音频类型失败：', err);}
				});
				this.$refs.responseDialog.open();
			},
			responseDialogConfirm() {
				/* uni.request({
					url: this.$baseUrl + `/user/device/setdeviceresponseword/${this.deviceUUID}/${this.reponseWord}`, // 后端设置响应音频类型
					header: {
						'token': uni.getStorageSync('token')
					},
					method: 'GET',
					success: (res) => {
						console.log(res);
						if (res.statusCode === 200 && res.data && res.data.data) {
							console.log('设置响应音频类型失败：',  res.data.data);
						} else {
							// console.error('设置响应音频类型失败：', res);
						}
					},
					fail: (err) => {
						console.error('设置响应音频类型失败：', err);
					}
				}); */
				console.log('当前选择的播放音频:', this.selectedResponseWord); // 调试用，查看当前选择的音频值
				const selectedAudioResponse = this.selectedResponseWord;              
				const message = {
					msg: "set_audio_response",
					data: String(selectedAudioResponse) // 20240710lUXIAOCHEN
				};              
				const opts = {
					topic: `LSY/app/${this.deviceUUID}`,
					message: JSON.stringify(message)
				};          
				this.$mqttTool.publish(opts).then(res => {
					console.log('音频选择已发送', res);
					uni.showToast({
						title: '音频设置已更新',
						icon: 'success',
						duration: 2000
					});
				}).catch(err => {
					console.error('发送音频选择失败', err);
					uni.showToast({
						title: '发送失败',
						icon: 'none',
						duration: 2000
					});
				});              
				this.$refs.responseDialog.close();
				
			},
			callDevice() {
				const uuid = this.deviceUUID;
				uni.navigateTo({url: `/pages/call/call?uuid=${uuid}`})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		display: flex;
		flex-direction: column;
		align-items: stretch;
	}

	.example {
		padding: 10px;
		background-color: #fff;
		margin: 10px;
		border-radius: 8px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	.form-row {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.label {
		width: 630rpx;
		color: #000000;
		padding-right: 30rpx;
	}

	.value {
		display: block;
		text-align: left;
		padding-left: 40rpx;
		transform: translateY(18rpx);
	}

	.form-item {
		display: flex;
		align-items: center;
		height: 80rpx;
		flex: 1;
		border: #e5e5e5 2rpx solid;
		border-radius: 5px;
	}

	.uni-input {
		margin-left: 10rpx;
		padding: 10rpx;
		font-size: 25rpx;
	}

	.tips-panel {
		width: 100%;
		font-size: 14px;
		color: #3e3d3e;
		word-break: break-all;
		height: 100px;
		/* 设置固定高度，确保滚动 */
		overflow: auto;
		/* 启用滚动 */
		overflow-y: scroll;
	}

	.panel-list {
		margin-top: 20rpx;
		padding: 10upx 20upx;
		border-bottom: 1px solid #eeeeee;
	}
</style>